/**
 * 
 */
package com.angis.fx.activity.search;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.widget.Toast;

public class CameraPicture extends Activity {
	private Preview mPreview;
	public static Bitmap pbitmap = null;
	public static boolean isShoot;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Hide the window title.
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		isShoot = false;
		// Create our Preview view and set it as the content of our activity.
		mPreview = new Preview(this, CameraPicture.this);
		setContentView(mPreview);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stubas
		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			Toast.makeText(this, "摄像机拍照", Toast.LENGTH_SHORT).show();
			isShoot = true;
			return mPreview.onKeyDown(keyCode, event);
		}
		if (keyCode == KeyEvent.FLAG_KEEP_TOUCH_MODE) {
			if (CameraPicture.pbitmap != null
					&& !CameraPicture.pbitmap.isRecycled()) {
				CameraPicture.pbitmap.recycle();
				CameraPicture.pbitmap = null;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}

// ----------------------------------------------------------------------

class Preview extends SurfaceView implements SurfaceHolder.Callback {
	SurfaceHolder mHolder;
	Camera mCamera;
	// private Bitmap mBitmap = null;
	Activity activity;

	Preview(Context context, Activity activity) {
		super(context);
		
		// Install a SurfaceHolder.Callback so we get notified when the
		// underlying surface is created and destroyed.
		mHolder = getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		this.activity = activity;
	}

	public void surfaceCreated(SurfaceHolder holder) {
		// The Surface has been created, acquire the camera and tell it where
		// to draw.
		mCamera = Camera.open();
		// Camera.Parameters p = mCamera.getParameters();
		// p.setRotation(90);
		try {
			mCamera.setPreviewDisplay(holder);
		} catch (IOException exception) {
			mCamera.release();
			mCamera = null;
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// Surface will be destroyed when we return, so stop the preview.
		// Because the CameraDevice object is not a shared resource, it's very
		// important to release it when the activity is paused.
		mCamera.stopPreview();
		mCamera.release();
		mCamera = null;
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		// Now that the size is known, set up the camera parameters and begin
		// the preview.
		Camera.Parameters parameters = mCamera.getParameters();
		// parameters.setPreviewSize(w, h);
		mCamera.setParameters(parameters);
		mCamera.startPreview();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			if (mCamera != null) {
				// if(mBitmap!=null && !mBitmap.isRecycled()){
				// mBitmap.recycle();
				// }
				if (CameraPicture.pbitmap != null
						&& !CameraPicture.pbitmap.isRecycled()) {
					CameraPicture.pbitmap.recycle();
					CameraPicture.pbitmap = null;
				}
				mCamera.takePicture(null, null, new Camera.PictureCallback() {

					public void onPictureTaken(byte[] data, Camera camera) {
						// TODO Auto-generated method stub
						Bitmap dstbmp = BitmapFactory.decodeByteArray(data, 0,
								data.length);
						Matrix matrix = new Matrix();
						//matrix.postScale(0.8f, 0.8f);
						matrix.postRotate(90);
						CameraPicture.pbitmap = Bitmap.createBitmap(dstbmp, 0,
								0, dstbmp.getWidth(), dstbmp.getHeight(),
								matrix, true);
						dstbmp.recycle();
						try {
							File f = new File(android.os.Environment
									.getExternalStorageDirectory()
									+ "/fx/" + new Date().getTime() + ".jpg");
							if (!f.getParentFile().exists()) {
								f.getParentFile().mkdirs();
							}
							f.createNewFile();
							BufferedOutputStream os = new BufferedOutputStream(
									new FileOutputStream(f));
							CameraPicture.pbitmap.compress(
									Bitmap.CompressFormat.JPEG, 80, os);
							os.flush();
							os.close();
							// Canvas canvas = mHolder.lockCanvas();
							// canvas.drawBitmap(mBitmap, 0, 0, null);
							// mHolder.unlockCanvasAndPost(canvas);
							// CameraPicture.this.finish();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						activity.finish();
					}

				});
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	//	
	// private Bitmap decodeFile(File f){
	// Bitmap b = null;
	// try {
	// //Decode image size
	// BitmapFactory.Options o = new BitmapFactory.Options();
	// o.inJustDecodeBounds = true;
	// BitmapFactory.decodeStream(new FileInputStream(f), null, o);
	// int scale = 1;
	// if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
	// scale = Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double)
	// Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
	// }
	//
	// //Decode with inSampleSize
	// BitmapFactory.Options o2 = new BitmapFactory.Options();
	// o2.inSampleSize = scale;
	// b = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
	// } catch (FileNotFoundException e) {
	// }
	// return b;
	// }

	// 拍照后输出图片
	// public Camera.PictureCallback pic = new Camera.PictureCallback() {
	//
	// public void onPictureTaken(byte[] data, Camera camera) {
	// // TODO Auto-generated method stub
	// mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
	// try {
	// File f = new File(android.os.Environment
	// .getExternalStorageDirectory()
	// + "/fx/" + new Date().getTime() + ".jpg");
	// if (!f.getParentFile().exists()) {
	// f.getParentFile().mkdirs();
	// }
	// f.createNewFile();
	// BufferedOutputStream os = new BufferedOutputStream(
	// new FileOutputStream(f));
	// mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, os);
	// CameraPicture.pbitmap = mBitmap;
	// os.flush();
	// os.close();
	// // Canvas canvas = mHolder.lockCanvas();
	// // canvas.drawBitmap(mBitmap, 0, 0, null);
	// // mHolder.unlockCanvasAndPost(canvas);
	// // CameraPicture.this.finish();
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// activity.finish();
	// }
	//
	// };
}